package com.test.schoolhelper.ui.activity;

import static android.Manifest.permission.MANAGE_EXTERNAL_STORAGE;
import static android.os.Environment.DIRECTORY_DOCUMENTS;

import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.webkit.MimeTypeMap;
import android.widget.SeekBar;

import androidx.annotation.NonNull;

import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.test.schoolhelper.R;
import com.test.schoolhelper.base.BaseActivity;
import com.test.schoolhelper.databinding.ActivityMusicBinding;
import com.test.schoolhelper.ui.service.MusicService;
import com.test.schoolhelper.utils.CalendarReminderUtils;
import com.test.schoolhelper.utils.LogUtils;
import com.test.schoolhelper.utils.ToastUtils;
import com.test.schoolhelper.utils.Tools;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

// TODO: 2024/5/29 音乐服务
public class MusicActivity extends BaseActivity<ActivityMusicBinding>
        implements View.OnClickListener, SeekBar.OnSeekBarChangeListener {

    private MusicService.Finder controller;
    private Intent intent;
    private RotateAnimation rotateAni;
private boolean download;

    @Override
    protected void initData() {
        super.initData();
        intent = new Intent(this, MusicService.class);
    }

    @Override
    protected void initClick() {

        getBinding().tvPause.setOnClickListener(this);
        getBinding().tvPlay.setOnClickListener(this);
        getBinding().ivBack.setOnClickListener(this);
        getBinding().seekBar.setOnSeekBarChangeListener(this);
        getBinding().tvDownload.setOnClickListener(this);
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_music;
    }

    @Override
    protected ActivityMusicBinding onCreateViewBinding(@NonNull LayoutInflater layoutInflater) {
        return ActivityMusicBinding.inflate(layoutInflater);
    }

    public Handler handler = new Handler(Looper.getMainLooper()) {
        public void handleMessage(Message message) {
            super.handleMessage(message);
            switch (message.what) {
                case 0:
                    Update();
                    break;
            }

        }
    };
    private boolean destroy;

    public void Update() {
        if (destroy) {
            return;
        }
        try {
            int currentTime = controller.getCurrentPosition();
            getBinding().seekBar.setProgress(currentTime);
            getBinding().tvProgress.setText(formatTime(currentTime));
        }catch (NullPointerException e){
            Log.d("MusicActivity","更新出错：" + e);
        }finally {
            handler.sendEmptyMessageDelayed(0, 500);
        }
    }

    private String formatTime(int length) {
        Date date = new Date(length);
        SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
        return sdf.format(date);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_play:
                if (!download){
                    ToastUtils.getInstance().show(this, "请先下载歌曲");
                    return;
                }
                intent.putExtra("play", 1);
                startService(intent);//开启服务
                MyConnection myConnection = new MyConnection();//建立新连接对象
                bindService(intent, myConnection, BIND_AUTO_CREATE);//建立和service连接
                rotate(0, 360);
                break;
            case R.id.tv_pause:
                if (!download){
                    ToastUtils.getInstance().show(this, "请先下载歌曲");
                    return;
                }

                intent.putExtra("play", 2);
                startService(intent);
                getBinding().ivHead.clearAnimation();
                break;
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_download:
                String url=getBinding().etUrl.getText().toString().trim();
                if (TextUtils.isEmpty(url)){
                    url="https://music.163.com/song/media/outer/url?id=2049512697";
                }
                downloadFile(url);
                break;
        }
    }

    private void downloadFile(String url) {
        String path=getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath() + File.separator + "music.mp3";
        if (new File(path).exists()){
            new File(path).delete();
        }

        FileDownloader.getImpl().create(url)
                .setPath(path)
                .setListener(new FileDownloadListener() {
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                    }

                    @Override
                    protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        runOnUiThread(() -> ToastUtils.getInstance().show(MusicActivity.this, "进度：" + soFarBytes + "/" + totalBytes));
                        ;
                    }

                    @Override
                    protected void blockComplete(BaseDownloadTask task) {
                    }

                    @Override
                    protected void retry(final BaseDownloadTask task, final Throwable ex, final int retryingTimes, final int soFarBytes) {
                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        Log.d("MusicActivity","下载完成！");
                        download=true;
                        runOnUiThread(() -> ToastUtils.getInstance().show(MusicActivity.this, "下载完成！"+path));
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                        Log.d("MusicActivity",e.toString());
                       runOnUiThread(() -> ToastUtils.getInstance().show(MusicActivity.this, "下载失败！"));
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {
                    }
                }).start();
    }

    /**
     * 旋转动画
     */
    public void rotate(float fd, float td) {
        //参数1：从哪个旋转角度开始,0表示从0度开始
        //参数2：转到什么角度,360表示旋转360度
        //后4个参数用于设置围绕着旋转的圆的圆心在哪里
        //参数3：确定x轴坐标的类型，有ABSOLUT绝对坐标、RELATIVE_TO_SELF相对于自身坐标、RELATIVE_TO_PARENT相对于父控件的坐标
        // Animation.RELATIVE_TO_SELF, 0.5f表示绕着自己的中心点进行动画
        //参数4：x轴的值，0.5f表明是以自身这个控件的一半长度为x轴
        //参数5：确定y轴坐标的类型
        //参数6：y轴的值，0.5f表明是以自身这个控件的一半长度为x轴
        rotateAni = new RotateAnimation(fd, td,
                Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF,
                0.5f);

        //设置动画执行的时间，单位是毫秒
        rotateAni.setDuration(10000);
        rotateAni.setFillAfter(true); // 设置保持动画最后的状态
        // 设置动画重复次数
        // -1或者Animation.INFINITE表示无限重复，正数表示重复次数，0表示不重复只播放一次
        rotateAni.setRepeatCount(-1);

        // 设置动画模式（Animation.REVERSE设置循环反转播放动画,Animation.RESTART每次都从头开始）
        rotateAni.setRepeatMode(Animation.RESTART);

        // 启动动画
        getBinding().ivHead.startAnimation(rotateAni);
    }


    @Override
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

    }

    @Override
    public void onStartTrackingTouch(SeekBar seekBar) {

    }

    @Override
    public void onStopTrackingTouch(SeekBar seekBar) {
        int progress = seekBar.getProgress();
        seekBar.setProgress(progress);
        controller.setProgress(progress);
    }

    class MyConnection implements ServiceConnection {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            ToastUtils.getInstance().show(MusicActivity.this, "服务已连接！");
            controller = (MusicService.Finder) service;
            int duration = controller.getDuration();
            getBinding().tvDuration.setText(formatTime(duration));
            getBinding().seekBar.setMax(duration);
            Update();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    }

    public void copyFilesFromRaw(int id) {//将raw/music.mp3拷贝到sd卡
        InputStream inputStream = getResources().openRawResource(id);
        readInputStream(getExternalFilesDir("music").getAbsolutePath() + File.separator + "music.mp3", inputStream);

    }

    /**
     * 读取输入流中的数据写入输出流
     *
     * @param storagePath 目标文件路径
     * @param inputStream 输入流
     */

    public static void readInputStream(String storagePath, InputStream inputStream) {
        File file = new File(storagePath);
        try {
            if (!file.exists()) {

                // 1.建立通道对象
                FileOutputStream fos = new FileOutputStream(file);
                // 2.定义存储空间
                byte[] buffer = new byte[inputStream.available()];
                // 3.开始读文件
                int lenght = 0;
                while ((lenght = inputStream.read(buffer)) != -1) {// 循环从输入流读取buffer字节
                    // 将Buffer中的数据写到outputStream对象中
                    fos.write(buffer, 0, lenght);
                }
                fos.flush();// 刷新缓冲区
                // 4.关闭流
                fos.close();
                inputStream.close();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        destroy = true;
        intent = new Intent(this, MusicService.class);
        stopService(intent);//停止服务
    }
}